package net.rock.eshop.controller.manage;

import net.rock.eshop.entity.Order;
import net.rock.eshop.exception.InvalidRequestException;
import net.rock.eshop.exception.ServerIOException;
import net.rock.eshop.exception.UnauthorizedOperationException;
import net.rock.eshop.service.OrderService;
import net.rock.eshop.utils.AdminChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/manage/order")
public class OrderManageController {
    @Autowired
    OrderService orderService;

    @Autowired
    private AdminChecker adminChecker;
    @GetMapping("/fetch")
    public List<Order> fetchAllOrder(@CookieValue(value = "sessionID", defaultValue = "") String sessionId) {
        if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            return orderService.fetchAllOrders();
        }
    }

    @PostMapping("/send")
    public void send(@CookieValue(value = "sessionID", defaultValue = "") String sessionId,
                     @RequestBody Map<String, String> body) {
        String id = body.get("id");
        if (id == null) {
            throw new InvalidRequestException();
        } else if (!adminChecker.checkAdmin(sessionId)) {
            throw new UnauthorizedOperationException();
        } else {
            orderService.send(id);
        }
    }

}
